<template>
  <div class="units-wrap">
    <el-row type="flex" justify="space-between" class="serach-form-wrap">
      <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
        <el-form-item>
          <el-select filterable @change="getTableData(1)" v-model="searchForm.orgId" placeholder="请选择业主单位">
            <el-option
              v-for="item in orgList"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <tree-select 
            v-model="searchForm.roleId"
            placeholder="请选择角色"
            filterable
            :width="200"
            :data="roleList"
            :defaultProps="roleDefaultProps"
            :checkedKeys="checkedRoleKeys"
            :nodeKey="roleNodeKey">
          </tree-select>
        </el-form-item>
        <el-form-item>
          <el-input
              placeholder="请输入姓名/账号/手机号"
              v-model="searchForm.name"
              clearable
              @keyup.enter.native="getTableData(1)">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="getTableData(1)">查询</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <div>
      <el-table
        v-loading="loading"
        ref="singleUnitTableList"
        :data="tableData"
        style="width: 100%">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="组织" prop="organizationName"></el-table-column>
        <el-table-column label="角色" prop="roleNames">
          <template slot-scope="scope">
            <span>{{ scope.row.roleNames.replace(/(,*$)/g,"") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账号" prop="accountName"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="职位" prop="postName"></el-table-column>
        <el-table-column label="手机号" prop="phone"></el-table-column>
        <!-- <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isDetach == 1" type="text" @click="deletePermissions(scope.row)" size="small">移除单位权限</el-button>
          </template>
        </el-table-column> -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="handleDetail(scope.row)" type="text" size="small">详情</el-button>
            <span class="dividing-line">|</span>
            <el-button @click="editUserInfo(scope.row)" type="text" size="small">编辑</el-button>
            <span class="dividing-line">|</span>
            <el-button @click="deleteUser(scope.row)" type="text" size="small">删除</el-button>
            <span class="dividing-line">|</span>
            <el-button @click="resetPasword(scope.row)" type="text" size="small">密码重置</el-button>
          </template>
        </el-table-column>
        <el-table-column type="expand" width='1'>
          <template slot-scope="props">
            <el-form label-position="left" label-width="120px" inline class="demo-table-expand" @submit.native.prevent>
              <el-form-item label="添加时间：">
                  <span>{{ formatDateTime(props.row.createDate) }}</span>
              </el-form-item>
              <el-form-item label="联网单位权限：">
                  <span>{{ props.row.permissionOrgNames }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="用户信息维护"
      width="600px"
      top='8vh'
      v-if="dialogBaseInfo"
      :visible.sync="dialogBaseInfo"
      @close="closeUserInfo"
      v-dialogDrag>
      <user-info-maintain :userInfo="userInfo" :orgList="notAllOrgList" :roleList="roleList" :closeUserInfo="closeUserInfo"></user-info-maintain>
    </el-dialog>
  </div>
</template>
<script>
import { getOrgList } from '@/api/org'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getOrgAuthUserList, detachUserOrgId } from '@/api/user'
import { getUcOrgList, getRoleAuthList, delUserDataById, resetPasswordDao } from '@/api/sysConfig'
import UserInfoMaintain from '../Dialog/UserInfoMaintain'
import utils from '@/utils/util'

export default {
  name:'Units',
  components: { 
    TreeSelect,
    UserInfoMaintain
  },
  data() {
    return {
      loading: true,
      dialogBaseInfo: false,
      searchForm: {
        orgId: '',
        roleId: '',
        name: '',
      },
      orgList: [], // 业主单位下拉框
      notAllOrgList: [], // 单位、组织结构树
      // 角色
      roleList: [],
      roleDefaultProps: {
        children: 'nodes',
        label: 'name',
        value: 'id'
      },
      roleNodeKey: 'id',
      checkedRoleKeys: [],
      // 列表
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userInfo: {} // 编辑对应的用户信息
    }
  },
  created() {
    let that = this
    that.getOrgList()
    that.getUcOrgList()
    that.getRoleList()
  },
  methods: {
    // 处理联网单位，id=73的增加disabled
    detailOrgData(data) {
      let arr = data
      for(let i=0, len=arr.length; i < len; i++) {
        if(arr[i].id == 73) {
          arr[i].disabled = true
        }
      }
      // 处理业主单位选项禁用（恶心）
      setTimeout(() => {
        let $arr = $('.self-org-tree .el-tree-node__label')
        
        for(var j=0; j < $arr.length; j++) {
            if($arr[j].textContent === '业主单位' || $arr[j].textContent === '联网单位') {
                $($arr[j]).addClass('is-disabled')
            }
        }
      }, 1000)
      return arr
    },
    getOrgList() {
      let that = this
      // 获取业主单位信息
      getOrgList({
        queryType: 0
      }).then(res => {
        if(res.status = 200) {
          that.orgList = res.data
          that.searchForm.orgId = res.data[0].organizationId
          that.getTableData()
        }
      })
    },
    getUcOrgList() {
      let that = this
      getUcOrgList({
        type: 1
      }).then(res => {
        that.notAllOrgList = that.detailOrgData(res.data)
      })
    },
    getRoleList() {
      let that = this
      let newArr = []
      getRoleAuthList().then(res => {
        newArr.push({
          name: '全部角色',
          id: '-1',
          nodes: res.data
        })
        that.roleList = newArr
        that.$nextTick(() => {
          // 默认选中全部
          that.checkedRoleKeys = '-1'.split(',')
        })
      })
    },
    getTableData(pageIndex, pageSize) {
      let that = this
      that.loading = true
      if (typeof(pageIndex) === 'number' || pageIndex) {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }
      let parames = {
        orgIds: that.searchForm.orgId,
        roleId : that.searchForm.roleId == -1 ? '' : that.searchForm.roleId,
        name: that.searchForm.name.trim(),
        pageIndex : that.currentPage - 1,
        pageSize : that.pageSize,
        queryType:1
      }
      getOrgAuthUserList(parames).then(res => {
        if(res.status === 200) {
          that.tableData = res.data
          that.total = res.total
          that.loading = false
        }
      })
    },
    handleSizeChange(pageSize) {
      this.getTableData(1, pageSize)
    },
    handleCurrentChange(n) {
      this.getTableData(n)
    },
    // 移除权限
    // deletePermissions(row) {
    //   // 阻止事件冒泡
    //   event.stopPropagation()
    //   let that = this
    //   let tipText = ''
    //   if (row) {
    //     tipText = row.permissionOrgIds.split(',').length > 1 ? `确定移除${row.name}的【${row.organizationName}】权限吗？` : `${row.name}当前只剩【${row.organizationName}】的权限，确定任然移除权限吗？`
    //     this.$confirm(tipText, '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning',
    //       roundButton: true
    //     }).then(() => {
    //       detachUserOrgId({
    //         orgId: row.organizationId,
    //         userAccount: row.accountName
    //       }).then(res => {
    //         if( res.status === 200) {
    //           that.$message({
    //             type: 'success',
    //             message: '删除成功!'
    //           })
    //           that.getTableData(1)
    //         }else{
    //           that.$message.error(res.info)
    //         }
    //       })
    //     }).catch(() => {})
    //   }
    // },
    closeUserInfo(refresh) {
      this.dialogBaseInfo = false
      if(typeof(refresh) === 'boolean' && refresh) {
        this.getTableData(this.userInfo.id?'':1)
      }
    },
    formatDateTime: function(value) {
      return utils.ilinkTimeformat.format(new Date(value), 'yyyy-MM-dd hh:mm:ss')
    },
    // 详情
    handleDetail(row) {
      if (row) {
        this.$refs.singleUnitTableList.toggleRowExpansion(row)
      }
    },
    // 编辑
    editUserInfo(row) {
      this.userInfo = row
      this.dialogBaseInfo = true
    },
    // 删除
    deleteUser(row) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      if (row) {
        this.$confirm('确认删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true
        }).then(() => {
          delUserDataById({id: row.userId}).then(res => {
            if( res.status === 200) {
              that.$message({
                type: 'success',
                message: '删除成功!'
              })
              setTimeout(() => {
                that.getTableData(1)
              }, 1000)
            }else{
              that.$message.error(res.info)
            }
          })
        }).catch(() => {

        })
      }
    },
    // 密码重置
    resetPasword(row) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      if (row) {
        that.$confirm('确认重置密码吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true
        }).then(() => {
          resetPasswordDao({
            userId: row.userId
          }).then(res => {
            that.$message({
              type: 'success',
              message: '重置密码成功!'
            })
          })
        }).catch(() => {

        })
      }
    }
  },
  watch: {
    roleIdSelect(val, oldVal) {
      if(val !== oldVal) {
        this.getTableData(1)
      }
    }
  },
  computed: {
    roleIdSelect() {
      return this.searchForm.roleId
    }
  }
}
</script>
<style lang="scss">
.units-wrap {
  .demo-table-expand {
    .el-form-item {
      display: block;
      margin-bottom: 0;
    }
  }
}
</style>
